/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.codeminer.parts.database.dao;

import org.codeminer.database.DatabaseConnection;
import org.codeminer.database.DatabaseException;
import org.codeminer.parts.database.sql.From;
import org.codeminer.parts.database.sql.SQL;
import org.codeminer.parts.library.Playlist;
import org.codeminer.parts.library.Song;
import org.codeminer.parts.server.users.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Daniel Wasilew <daniel.wasilew@codeminer.org>
 */
public final class PlaylistDAO extends DAO {

    private static final String COLUMN_NAME_CREATIONUSER = "Creation_User";
    private static final String COLUMN_NAME_ID = "Playlist_Id";
    private static final String COLUMN_NAME_ISGLOBAL = "Is_Global";
    private static final String COLUMN_NAME_NAME = "Playlist_Name";
    private static final String PLAYLIST_TABLE_NAME = "Playlists";

    private PlaylistDAO() {
    }

    public static Playlist store(Playlist playlist, User owner, DatabaseConnection connection) throws DatabaseException {
        connection.accuireWriteLock();
        try {
            updateAndGetNextId(connection, playlist);
            String insertStatement = SQL.insertInto(PLAYLIST_TABLE_NAME).
                    values().
                    value(playlist.getOid()).
                    value(playlist.getName()).
                    value(playlist.isGlobal()).
                    value(owner.getName()).toSQL();
            executeInsert(connection, insertStatement);
            return playlist;
        } finally {
            connection.releaseWriteLock();
        }
    }

    private static List<Playlist> fetchFromDatabase(String query, DatabaseConnection connection) throws DatabaseException {
        ResultSet resultSet = null;
        try {
            resultSet = connection.createStatement().executeQuery(query);
            List<Playlist> result = new LinkedList<>();
            while (resultSet.next()) {
                long oid = resultSet.getLong(COLUMN_NAME_ID);
                String name = resultSet.getString(COLUMN_NAME_NAME);
                final Playlist playlist = new Playlist();
                playlist.setName(name);
                playlist.setOid(oid);
                playlist.setGlobal(resultSet.getBoolean(COLUMN_NAME_ISGLOBAL));
                result.add(playlist);
            }
            return result;
        } catch (SQLException ex) {
            throw new DatabaseException(ex);
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException ignored) {

                }
            }
        }
    }

    public static List<Playlist> get(Playlist searchCriteria, User user, DatabaseConnection connection) throws DatabaseException {
        try {
            connection.accuireReadLock();
            String query = null;
            From select = SQL.select().from(PLAYLIST_TABLE_NAME);
            if (searchCriteria == null) {
                query = select.toSQL();
            } else if (searchCriteria.getOid() != -1) { //search by oid
                query = select.where(COLUMN_NAME_ID).is(searchCriteria.getOid()).toSQL();
            } else if (searchCriteria.getName() != null) { //search by name
                query = select.where(COLUMN_NAME_NAME).is(searchCriteria.getName()).toSQL();
            }
            return fetchFromDatabase(query, connection);
        } finally {
            connection.releaseReadLock();
        }
    }

    public static List<Playlist> get(User user, DatabaseConnection connection) throws DatabaseException {
        String toSQL = SQL.select().from(PLAYLIST_TABLE_NAME).where(COLUMN_NAME_CREATIONUSER).is(user.getName()).or(COLUMN_NAME_ISGLOBAL).is(true).toSQL();
        try {
            connection.accuireReadLock();
            return fetchFromDatabase(toSQL, connection);
        } finally {
            connection.releaseReadLock();
        }
    }

    public static List<Song> getSongs(Playlist playlist, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiable(playlist);

        connection.accuireReadLock();
        try {
            String songsQuery = SQL.select("Song_Id").from("SONGS_FOR_PLAYLIST").where(COLUMN_NAME_ID).is(playlist.getOid()).toSQL();

            List<Long> songIds = queryIds(songsQuery, "Song_Id", connection);
            List<Song> result = new LinkedList<>();
            for (Long songId : songIds) {
                result.addAll(SongDAO.get(Song.byOId(songId), connection));
            }
            return result;
        } finally {
            connection.releaseReadLock();
        }

    }

    public static void addSongToPlaylist(Playlist playlist, Song song, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiables(song, playlist);

        List<Song> currentSongs = getSongs(playlist, connection);
        if (currentSongs.contains(song)) {
            return;
        }

        String insert = SQL.insertInto("SONGS_FOR_PLAYLIST").values().value(playlist.getOid()).value(song.getOid()).toSQL();
        connection.accuireWriteLock();
        try {
            executeInsert(connection, insert);
        } finally {
            connection.releaseWriteLock();
        }
    }

    public static void removeSongToPlaylist(Playlist playlist, Song song, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiables(song, playlist);

        String delete = SQL.delete().from("SONGS_FOR_PLAYLIST").where("Song_Id").is(song.getOid()).toSQL();
        connection.accuireWriteLock();
        try {
            executeUpdate(connection, delete);
        } finally {
            connection.releaseWriteLock();
        }
    }

    public static boolean delete(Playlist playlist, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiable(playlist);
        connection.accuireWriteLock();
        try {
            String deleteStatement = SQL.delete().from("Playlists").where(COLUMN_NAME_ID).is(playlist.getOid()).toSQL();
            return executeUpdate(connection, deleteStatement);
        } finally {
            connection.releaseWriteLock();
        }
    }

    public static boolean update(Playlist playlist, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiable(playlist);

        connection.accuireWriteLock();
        try {
            String query = SQL.update(PLAYLIST_TABLE_NAME).
                    set(COLUMN_NAME_NAME, playlist.getName()).
                    where(COLUMN_NAME_ID).is(playlist.getOid()).toSQL();
            return executeUpdate(connection, query);
        } finally {
            connection.releaseWriteLock();
        }
    }
}
